import React, { PureComponent }        from "react"
import styled, { keyframes }           from 'styled-components'
// import AlertBox from "./AlertBox"
import { getGift }                     from './DrawData'
import Header                          from '../../../components/Header/ProductHeader';
import './lottery.less';
import Util                            from '../../../utils';
import {
    Link, 
    withRouter
}                                      from 'react-router-dom';
import { 
    connect 
}                                      from "react-redux";
import * as actions                    from '../../../store/action/homepage';
import { actionPrize }                 from '../../../api/home';

// common
const grayColor = "#999999"
const activeColor = "#FFA488"
const btnBg = "#33CCFF"
const btnClickBg = "#FFA488"
const minZindex = 30

const zoomInDown = keyframes`
    from {
        opacity: 0;
        transform: scale3d(.1, .1, .1) translate3d(0, -1000px, 0);
        animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
    }
    60% {
        opacity: 1;
        transform: scale3d(.475, .475, .475) translate3d(0, 60px, 0);
        animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
    }
`;

const ClearFix = styled.div`
    &:before,&:after{
        display:table;
        content:'';
        clear:both;
    }
`;

const GiftBox = styled(ClearFix)`
`;

const GiftItem = styled.div`
    width:86px;
    height:86px;
    position:absolute;
    box-sizing:border-box;
    border-radius:5px;
    border:2px solid;
    border-color:${props => props.active ? activeColor : grayColor};
    background-color:${props => props.active ? "#146c8a" : "#ffffff"};
    .gift-name{
        text-align:center;
        font-size:14px;
        color:${props => props.active ? activeColor : grayColor};
    }
`;

const GiftImg = styled.div`
    width:48px;
    height:48px;
    margin:0 auto;
    background-image:url(${props => props.iconSrc});
`;

const DrawBtn = styled.button`
    outline:none;
    border:0;
    width:86px;
    height:86px;
    position:absolute;
    left:92px;
    top:92px;
    z-index:10;
    background-color:${props => props.isClicking ? btnClickBg : btnBg};
    box-shadow:1px 1px 20px 16px ${props => props.isClicking ? "#cc6140" : "#29b6e4"} inset;
    border-radius:5px;
    cursor:pointer;
    padding:0;
    font-size:20px;
    /* color:${props => props.isClicking ? grayColor : activeColor}; */
`;
// got dialog
const DrawGiftDialog = styled(ClearFix)`
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
    display:${props => props.show ? "block" : "none"};
    z-index:${minZindex + 15};
    cursor:pointer;
`;

const GotGift = styled.div`
    width: 200px;
    height: 200x;
    margin:0 auto;
    margin-top:116px;
    background-color: #FFC93C;
    border-radius: 5px;
    box-shadow: 1px 1px 20px 16px #FFA60D inset;
    padding: 25px;
    animation: ${zoomInDown} 1.4s;
    position:relative;
    .got-img{
        display:block;
        width:100px;
        height:100px;
        margin:20px auto;
        background-image:url(${props => props.giftSrc});
        background-color:#ffffff;
        background-size:100% 100%;
        border-radius: 12px;
    }
`;

const CloseDialogBtn = styled.button`
    outline:none;
    border:0;
    display:block;
    position: absolute;
    width: 60px;
    height: 60px;
    background-image: url('/images/close.svg');
    background-size: auto 100%;
    background-color:transparent;
    cursor:pointer;
    left:50%;
    transform:translateX(-50%);
    top:-60px;
`;

function GetDrawBtn({ isClicking, onClick }) {
    return <DrawBtn isClicking={isClicking} onClick={onClick}>{isClicking ? "抽奖中..." : "开始"}</DrawBtn>
}

// mock endStopIndex
function getRandomNum(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

class Lottery extends PureComponent {
    constructor(props) {
        super(props)
        this.state = {
            giftList: getGift(),
            // 一圈的总长度，礼物总数量
            stepCount: getGift().length,
            // 剩余抽奖次数，接口返回
            myCount: 5,
            // 转动激活位置默认：1，动态，可设置(>=1&&<=stepCount)
            activeIndex: 1,
            // 最终要停下的位置：接口返回(>=1&&<=stepCount)
            endStopIndex: 14,
            // 抽奖是否正在进行中
            isDrawing: false,
            // 转速   分别为最后0,1,2,3,4,5圈的转速
            speed: [336, 168, 84, 42, 42, 42],
            // 抽獎結果的禮物名字
            showDialog: false,
            gotGift: null,
            // 消息提示框
            message: null,
            messageType: null,
            animationName: null,
        };
        // 开启转盘的定时器
        this.timer = null;
        //alert message list
        this.messageInfo = {
            success: {
                message: "恭喜您中奖了!",
                animationName: null
            },
            warning: {
                message: "抽奖进行中，请稍后再试!",
                animationName: "slideInLeft"
            },
            error: {
                message: "抽奖次数不足,抓紧去完成任务获得抽奖资格吧~",
                animationName: "shake",
            },
        }

        this.startDraw = this.startDraw.bind(this);
    }

    componentDidMount() {
        console.log(`lottery mounted`, this.props.homepage.prize);
        // if (!this.props.homepage.prize.id) {
        //     this.props.fetchPrize(1);
        // }
    }

    componentWillUnmount() {
        if (this.timer) {
            clearTimeout(this.timer);
        }
    }

    startDraw = e => {
        // 抽奖进行中禁止点击，抽奖次数<=0禁止点击
        const { isDrawing } = this.state;
        const {
            prize
        } = this.props.homepage;
        const { prizes } = prize;

        var myCount = prizes.length;

        if (isDrawing) {
            this.alertMessage("warning");
        } else {
            if (myCount <= 0) {
                this.alertMessage("error");
            } else {
                actionPrize(prize.id)
                .then((res) => {
                    console.log('抽奖结果', res);
                    if (res && res.ret == 0 ) {
                        let myCount = myCount - 1;
                        this.setState({ isDrawing: true,  endStopIndex: res.data.id, myCount }, this.startRun);
                        console.log(`最終要停在:${this.state.endStopIndex}`)
                    }
                })
                .catch((e) => {
                    console.log('抽奖失败', e);
                });

                // 假装发了一个ajax请求：sucsess,catch,error
                // setTimeout(() => {
                //     let result = {
                //         ret_code: "0", //success
                //         endStopIndex: getRandomNum(1, myCount),
                //     }
                //     // 是否正抽可能还需要接口来限制：如是否绑定手机号、、
                //     if (result.ret_code === "0") {
                //         let { endStopIndex } = result;
                //         let myCount = myCount - 1;
                //         // 开启转盘,開啟限制再次點擊抽獎
                //         this.setState({ isDrawing: true, endStopIndex, myCount }, this.startRun);
                //         console.log(`最終要停在:${this.state.endStopIndex}`)
                //     } else if (result.ret_code === "error") {
                //     }
                // }, 300)
            }
        }
    }

    startRun() {
        // 总共需要转的圈数
        let leftRound = this.state.speed.length - 1;
        this.addOneStep({ isContinue: true, leftRound })
    }

    /*
    * 每次增加一步，满一圈，总圈数-1同时速度变慢，直到最后一圈停在指定位置
    * 直到知道结果，慢慢变慢速度，停在结果那;
    * 转盘停到结果值时，重置初始值（{isDrawing:false}）；
    * 
    * Function addOneStep
    * 奖品位置移动一步
    * @isContinue   {Booleans}  是否应该继续这个定时器
    * @leftRound        {Number}    剩余几圈  3代表一个无限大的值，因为还不知道结果
    */
    addOneStep = (params) => {
        let { activeIndex, stepCount, speed } = this.state;
        let { isContinue, leftRound } = params;
        const {
            prizes
        } = this.props.homepage.prize;
        activeIndex += 1;
        if (isContinue) {
            // 如果到超过奖品个数，重置为1
            if (activeIndex > stepCount) {
                console.log(`转了${leftRound}圈`);
                leftRound -= 1;
                activeIndex = 1;
            }
            // 如果已经到最后一圈了  且  已经到了指定要中奖的位置了  就不需要继续了
            if (leftRound === 0 && activeIndex === this.state.endStopIndex) {
                console.log(`現在停在:${this.state.endStopIndex}`);
                isContinue = false;
            }
            this.setState({ activeIndex });
            const nextParams = {
                isContinue,
                leftRound,
            };
            this.timer = setTimeout(() => {
                this.addOneStep(nextParams)
            }, speed[leftRound]);
        } else {
            clearTimeout(this.timer);
            this.timer = null;
            // let gotGift = this.state.giftList[this.state.endStopIndex - 1];
            let gotGift = {
                name: prizes[this.state.endStopIndex - 1].title,
                icon: prizes[this.state.endStopIndex - 1].cover
            };
            this.setState({
                isDrawing: false,
                gotGift,
                showDialog: true,
            });
            this.alertMessage("success")
        }
    }

    alertMessage(messageType) {
        let { message, animationName } = this.messageInfo[messageType];
        this.setState({ messageType, message, animationName });
    }

    //移除alert的回调
    removeAlert = () => {
        this.setState({ message: null, messageType: null, animationName: null })
    }

    hideGotDialog = () => {
        this.setState({ showDialog: false })
    }

    getPrize(prize, id) {
        return {
            id: id, 
            type: 'prize',
            prize: prize
        }
    }
    getSordGirdRow(prizes, offset = 0, shift = false) {
        let res = [];
        for (let i = 0; i < 3; i++) {
            let curent = shift ? prizes[2 - i] : prizes[i];
            let id = shift ? 3 - i + offset : i + 1;
            if (curent) {
                res.push({
                    id: id,
                    type: 'prize',
                    prize: curent,
                });
            } else {
                res.push({
                    type: 'empty'
                });
            }
        }   
        return res;
    }

    renderGiftGird() {
        // readonly
        const {
            giftList,
            activeIndex,
            isDrawing,
            showDialog,
            gotGift,
            myCount,
            message,
            messageType,
            animationName,
        } = this.state;

        const {
            prizes
        } = this.props.homepage.prize;
        
        // var prizes = [1,2,3,4];

        if (!prizes) return null;
        var rows = [];
        if (prizes.length < 4) {
            rows.push(this.getSordGirdRow(prizes));
            rows.push([{type:'empty'},{type:'start'},{type:'empty'}]);
        } else if (prizes.length < 6) {
            rows.push(this.getSordGirdRow(prizes));
            prizes.length == 4 ? rows.push([{type:'empty'}, {type:'start'}, this.getPrize(prizes[3], 3)]) : 
                                 rows.push([this.getPrize(prizes[4], 5), {type:'start'}, this.getPrize(prizes[3], 4)]);
        } else {
            rows.push(this.getSordGirdRow(prizes));
            prizes.length < 8 ?  rows.push([{type:'empty'}, {type:'start'}, this.getPrize(prizes[3], 3)]) : 
                                 rows.push([this.getPrize(prizes[7], 8), {type:'start'}, this.getPrize(prizes[3], 4)]);
            rows.push(this.getSordGirdRow(prizes.slice(4,7), 4, true));
        }

        return rows.map((row, index) => {
            return (
                <div className="giftItemRow">
                    {
                        row.map((gift, gindex) => {
                            if (gift.type == 'start') {
                                return (
                                    <div className="giftItem startBtn" onClick={this.startDraw}>
                                        <span>{isDrawing ? "抽奖中..." : "开始"}</span>
                                    </div>
                                )
                            } else if (gift.type == 'empty') {
                                return (
                                    <div className="giftItem emptyBox">
                                    </div>
                                )
                            } else if (gift) {
                                const className = activeIndex == gift.id ? "giftItem giftItemActive" : "giftItem";
                                return (
                                    <div className={className} style={{backgroundImage: `url(${gift.prize.cover})`}}>
                                        <span className="title">{gift.prize.title}</span>
                                    </div>
                                )
                            } else {
                                return null;
                            }
                        })
                    }
                </div>
            )
        });
    }

    render() {
        // readonly
        const {
            activeIndex,
            showDialog,
            gotGift,
        } = this.state;
        
        const {
            prize
        } = this.props.homepage;
        const getIsActive = (item) => (
            item.id === activeIndex ? 1 : 0
        )
        // <GiftItem active={getIsActive(gift)}
        //     iconSrc={gift.icon}
        //     left={gift.left}
        //     top={gift.top}
        //     key={index}>
        //     <GiftImg iconSrc={gift.icon}></GiftImg>
        //     <div className="gift-name">{gift.name}X{gift.count}</div>
        // </GiftItem>
        // <GetDrawBtn isClicking={isDrawing} onClick={this.startDraw} />
        return (
            <div className="draw-box" style={{height: Util.viewport().height}}>
                <Header title="抽奖" />
                {/* tipsBox */}
                {/* {
                    message ?
                        <AlertBox message={message}
                            type={messageType}
                            animation={animationName}
                            hideAlert={this.removeAlert}></AlertBox> : null
                } */}

                {/* main */}
                <div className="DrawWrap">
                    <div className="DrawBg">
                        <DrawGiftDialog show={showDialog}>
                            {
                                showDialog ? <GotGift giftSrc={gotGift.icon}>
                                    <div className="closeBtn" onClick={this.hideGotDialog}></div>
                                    <div className="got-img"></div>
                                    <p className="got-name">{gotGift.name}</p>
                                </GotGift> : null
                            }
                        </DrawGiftDialog>
                        <div className="GiftBox ClearFix"> 
                            {
                                this.renderGiftGird()
                            }
                        </div>
                        <div className="prize-cost">将消耗 {prize.consume_score} 积分</div>
                    </div>
                </div>
            </div>
        )
    }
}

export default withRouter(connect((state)=>{return {...state}}, actions)(Lottery));